﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.WeChatUserInfoSync
{
    public class SyncUserThread
    {
        public Thread CreatorThread;
        private readonly ILog _fileLog = LogManager.GetLogger(typeof (SyncUserThread));

        private readonly WxInterUserFunc _wxInterUserFunc = new WxInterUserFunc();
        private readonly WechatInfoBLL _weChatInfoBll = new WechatInfoBLL();

        public delegate void FinishSyncUserInfo(object sender, EventArgs e);

        public event FinishSyncUserInfo OnEventSyncUserInfo;

        private string _strAppId;
        public bool BRunning;

        public int NDoneUnion;

        public SyncUserThread(string appId)
        {
            _strAppId = appId;
            NDoneUnion = 0;
        }

        public void CreateNewThread()
        {
            CreatorThread = new Thread(ThreadMain) {IsBackground = true};
        }

        public void StartThread()
        {
            NDoneUnion = 0;
            CreatorThread.Start();
            BRunning = true;
        }

        public void StopThread()
        {
            BRunning = false;
        }

        private void ThreadMain()
        {
            try
            {
                var wechatInfo = _weChatInfoBll.GetWeChatInfoByAppId(_strAppId);


                var firstWeChatUser = WechatUserBLL.Instance.GetFisrtWeChatUserInfoNoUnionId(wechatInfo.Id);
                if (firstWeChatUser == null || firstWeChatUser.Id == 0)
                {
                    BRunning = false;
                    return;
                }

                var lsWeChatUser = WechatUserBLL.Instance.GetWeChatUserInfoNoUnionId(2000, firstWeChatUser.Id, wechatInfo.Id);
                if (lsWeChatUser == null || lsWeChatUser.Count == 0)
                {
                    BRunning = false;
                    return;
                }

                while (lsWeChatUser != null && lsWeChatUser.Count > 0 && BRunning)
                {
                    var nMinId = 0;
                    foreach (var wechatUser in lsWeChatUser)
                    {
                        var strAccessToken = _wxInterUserFunc.GetWxToken(wechatInfo.AppId, wechatInfo.Secret, wechatInfo.WechatId);
                        if (string.IsNullOrWhiteSpace(strAccessToken))
                        {
                            _fileLog.Error("SyncUserThread | ThreadMain: Error AccessToken");
                            MessageBox.Show("Token Failed");
                            return;
                        }

                        nMinId = wechatUser.Id;
                        var wechatUserUnionInfo = new WxUserInfo();
                        try
                        {
                            wechatUserUnionInfo = _wxInterUserFunc.GetUserInfoIncludeUnion(wechatInfo.AppId, strAccessToken, wechatUser.OpenId,
                            wechatInfo.Secret, wechatInfo.WechatId);
                            if (wechatUserUnionInfo == null || string.IsNullOrWhiteSpace(wechatUserUnionInfo.openid))
                            {
                                _fileLog.Error(
                                    "SyncUserThread | ThreadMain | Cannot get wechat user info by UnionWay - " + wechatUser.OpenId);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            _fileLog.Error(
                                "SyncUserThread | ThreadMain | Cannot get wechat user info by UnionWay - " +
                                wechatUser.OpenId + " " + ex.Message);
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(wechatUserUnionInfo.openid) ||
                            wechatUserUnionInfo.subscribe == 0)
                        {
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(wechatUserUnionInfo.unionid))
                        {
                            continue;
                        }
                        var formatToTime =
                            _wxInterUserFunc.FormatToTime(
                                wechatUserUnionInfo.subscribe_time.ToString(CultureInfo.InvariantCulture));

                        wechatUser.NickName = wechatUserUnionInfo.nickname;
                        wechatUser.Sex = wechatUserUnionInfo.sex;
                        wechatUser.Province = wechatUserUnionInfo.province;
                        wechatUser.City = wechatUserUnionInfo.city;
                        wechatUser.Country = wechatUserUnionInfo.country;
                        wechatUser.Headimgurl = wechatUserUnionInfo.headimgurl;
                        wechatUser.Unionid = wechatUserUnionInfo.unionid;
                        wechatUser.WeChatInfoId = wechatInfo.Id;
                        wechatUser.Subscribe = wechatUserUnionInfo.subscribe;
                        if (formatToTime != null)
                        {
                            wechatUser.SubscribeTime = wechatUserUnionInfo.subscribe == 1
                                ? (DateTime)formatToTime
                                : Convert.ToDateTime("1900/01/01 00:00:00");
                        }
                        else
                        {
                            wechatUser.SubscribeTime = DateTime.Now;
                        }
                        WechatUserBLL.Instance.Update(wechatUser);
                        NDoneUnion++;
                        OnEventSyncUserInfo(this, new EventArgs());
                    }

                    lsWeChatUser = WechatUserBLL.Instance.GetWeChatUserInfoNoUnionId(2000, nMinId, wechatInfo.Id);
                }
                BRunning = false;
            }
            catch (Exception ex)
            {
                _fileLog.Error(
                                "SyncUserThread | ThreadMain | Cannot get wechat user info by UnionWay - "  + ex.Message);
            }

            BRunning = false;
        }
    }
}
